package com.jjb.saas.gen.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.jjb.saas.gen.entity.GenTable;
import com.jjb.saas.gen.constants.GenConstants;
import com.jjb.saas.gen.entity.GenTableColumn;
import org.apache.velocity.VelocityContext;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * 模板工具类
 * 
 * @author wgg
 */
public class VelocityUtils
{
    /** 项目空间路径 */
    private static final String PROJECT_PATH = "main/java";

    /** mybatis空间路径 */
    private static final String MYBATIS_PATH = "main/resources/mapper";

    /** 默认上级菜单，系统工具 */
    private static final String DEFAULT_PARENT_MENU_ID = "3";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTable genTable)
    {
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String packageName = genTable.getPackageName();
        String tplCategory = genTable.getTplCategory();
        String functionName = genTable.getFunctionName();

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tplCategory", genTable.getTplCategory());
        velocityContext.put("tableName", genTable.getTableName());
        velocityContext.put("tableComment", genTable.getTableComment());
        velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
        velocityContext.put("ClassName", genTable.getClassName());
        velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        velocityContext.put("moduleName", genTable.getModuleName());
        velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
        velocityContext.put("businessName", genTable.getBusinessName());
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("packageName", packageName);
        velocityContext.put("author", genTable.getFunctionAuthor());
        velocityContext.put("datetime", DateUtil.date());
        velocityContext.put("pkColumn", genTable.getPkColumn());
        velocityContext.put("importList", getImportList(genTable));
        velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        velocityContext.put("columns", genTable.getColumns());
        velocityContext.put("table", genTable);
        velocityContext.put("repetition", "0");
        for(GenTableColumn genTableColumn : genTable.getColumns()){
            if(genTableColumn.isRepetition()){
                velocityContext.put("repetition", "1");
                break;
            }
        }
        velocityContext.put("isSub", false);
        velocityContext.put("isMain", false);
        if(ObjectUtil.isNotEmpty(genTable.getSubTableName())){
            velocityContext.put("isMain", true);
            String[] subTableNames = genTable.getSubTableName().split(",");
            velocityContext.put("subTableNames", Arrays.asList(subTableNames));
            String[] fks = genTable.getSubTableFkName().split("_");
            StringBuffer fkFieldUppName = new StringBuffer();
            StringBuffer fkFieldLowName = new StringBuffer();
            for (String fk : fks) {
                if(ObjectUtil.isEmpty(fkFieldLowName)){
                    fkFieldLowName.append(fk);
                }else{
                    fkFieldLowName.append(fk.substring(0,1).toUpperCase()+fk.substring(1));
                }
                fkFieldUppName.append(fk.substring(0,1).toUpperCase()+fk.substring(1));
            }
            velocityContext.put("fkFieldUppName", fkFieldUppName.toString());
            velocityContext.put("fkFieldLowName", fkFieldLowName.toString());
        }

        if(ObjectUtil.isNotEmpty(genTable.getSubTableFkName())&&ObjectUtil.isEmpty(genTable.getSubTableName())){
            velocityContext.put("isSub", true);
            velocityContext.put("subTableFkName", genTable.getSubTableFkName());
            String[] fks = genTable.getSubTableFkName().split("_");
            StringBuffer fkFieldUppName = new StringBuffer();
            StringBuffer fkFieldLowName = new StringBuffer();
            for (String fk : fks) {
                    if(ObjectUtil.isEmpty(fkFieldLowName)){
                        fkFieldLowName.append(fk);
                    }else{
                        fkFieldLowName.append(fk.substring(0,1).toUpperCase()+fk.substring(1));
                    }
                fkFieldUppName.append(fk.substring(0,1).toUpperCase()+fk.substring(1));
            }
            velocityContext.put("fkFieldUppName", fkFieldUppName.toString());
            velocityContext.put("fkFieldLowName", fkFieldLowName.toString());
        }
        //setMenuVelocityContext(velocityContext, genTable);
        /*if (GenConstants.TPL_TREE.equals(tplCategory))
        {
            setTreeVelocityContext(velocityContext, genTable);
        }
        if (GenConstants.TPL_SUB.equals(tplCategory))
        {
            setSubVelocityContext(velocityContext, genTable);
        }*/
        return velocityContext;
    }

    /**
     * 添加枚举的相关参数
     * @param genTableColumn
     * @return
     */
    public static void addPrepareContext(GenTableColumn genTableColumn,VelocityContext velocityContext){
        velocityContext.put("enumClassName",genTableColumn.getEnumClassName());
        velocityContext.put("enumTypeName",genTableColumn.getEnumTypeName());
        velocityContext.put("enumDatas",genTableColumn.getEnumHelpers());
        velocityContext.put("enumClassInfo",genTableColumn.getEnumClassInfo());
    }



    public static void setMenuVelocityContext(VelocityContext context, GenTable genTable)
    {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String parentMenuId = getParentMenuId(paramsObj);
        context.put("parentMenuId", parentMenuId);
    }

    public static void setTreeVelocityContext(VelocityContext context, GenTable genTable)
    {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String treeCode = getTreecode(paramsObj);
        String treeParentCode = getTreeParentCode(paramsObj);
        String treeName = getTreeName(paramsObj);

        context.put("treeCode", treeCode);
        context.put("treeParentCode", treeParentCode);
        context.put("treeName", treeName);
        context.put("expandColumn", getExpandColumn(genTable));
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE))
        {
            context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        if (paramsObj.containsKey(GenConstants.TREE_NAME))
        {
            context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME));
        }
    }

    public static void setSubVelocityContext(VelocityContext context, GenTable genTable)
    {
        GenTable subTable = genTable.getSubTable();
        String subTableName = genTable.getSubTableName();
        String subTableFkName = genTable.getSubTableFkName();
        String subClassName = genTable.getSubTable().getClassName();
        String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);

        context.put("subTable", subTable);
        context.put("subTableName", subTableName);
        context.put("subTableFkName", subTableFkName);
        context.put("subTableFkClassName", subTableFkClassName);
        context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
        context.put("subClassName", subClassName);
        context.put("subclassName", StringUtils.uncapitalize(subClassName));
        context.put("subImportList", getImportList(genTable.getSubTable()));
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(GenTable table,String tplCategory)
    {
        List<String> templates = new ArrayList<String>();

        if(ObjectUtil.isNotEmpty(table.getSubTableFkName())&&ObjectUtil.isEmpty(table.getSubTableName())){
            templates.add("vm/java/domain/domainvo.java.vm");
            templates.add("vm/java/infrastructure/mapper.java.vm");
            templates.add("vm/java/infrastructure/do.java.vm");
          //  templates.add("vm/java/infrastructure/queryservice.java.vm");
          //  templates.add("vm/java/infrastructure/queryserviceimpl.java.vm");
            templates.add("vm/java/infrastructure/repositoryimpl.java.vm");
            templates.add("vm/java/infrastructure/repository.java.vm");
            templates.add("vm/xml/mapper.xml.vm");
        }else {
            templates.add("vm/java/client/addcmd.java.vm");
            templates.add("vm/java/app/addcmdexe.java.vm");
            templates.add("vm/java/app/cmdconvertor.java.vm");
            templates.add("vm/java/client/co.java.vm");
            templates.add("vm/java/app/delcmdexe.java.vm");
            templates.add("vm/java/infrastructure/do.java.vm");
            templates.add("vm/java/infrastructure/doconvertor.java.vm");
            templates.add("vm/java/domain/domaine.java.vm");
            //templates.add("vm/java/domain/domainservice.java.vm");
            templates.add("vm/java/domain/domainability.java.vm");
            templates.add("vm/java/domain/gateway.java.vm");
            templates.add("vm/java/infrastructure/gatewayimpl.java.vm");
            templates.add("vm/java/app/listqueryexe.java.vm");
            templates.add("vm/java/infrastructure/mapper.java.vm");
            templates.add("vm/java/infrastructure/queryservice.java.vm");
            templates.add("vm/java/infrastructure/queryserviceimpl.java.vm");
            templates.add("vm/java/infrastructure/repositoryimpl.java.vm");
            templates.add("vm/java/infrastructure/repository.java.vm");
            templates.add("vm/java/client/updatecmd.java.vm");
            templates.add("vm/java/app/updatecmdexe.java.vm");
            templates.add("vm/xml/mapper.xml.vm");
            if (GenConstants.TPL_TREE.equals(tplCategory)) {
                templates.add("vm/java/adapter/controllertree.java.vm");
                templates.add("vm/java/client/treequery.java.vm");
                templates.add("vm/java/app/treequeryexe.java.vm");
                templates.add("vm/java/app/treeservicei.java.vm");
                templates.add("vm/java/app/treeserviceimpl.java.vm");
            } else {
                templates.add("vm/java/adapter/controller.java.vm");
                templates.add("vm/java/client/pageqry.java.vm");
                templates.add("vm/java/app/pagequeryexe.java.vm");
                templates.add("vm/java/app/servicei.java.vm");
                templates.add("vm/java/app/serviceimpl.java.vm");
            }
        }
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTable genTable)
    {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务路劲
        String businessName = genTable.getBusinessName().replace(".","/");

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        //String projectName = "yyjx-hsyj-";
        Environment environment = SpringUtil.getApplicationContext().getBean(Environment.class);
        String projectName = environment.getProperty("gen.projectName");
        String vuePath = "vue";
        String adapterPath = projectName+moduleName+"-adapter/src/"+javaPath;
        String appPath = projectName+moduleName+"-app/src/"+javaPath;
        String enumPath = projectName+moduleName+"-enums/src/"+javaPath;
        String clientPath = projectName+moduleName+"-client/src/"+javaPath;
        String domainPath = projectName+moduleName+"-domain/src/"+javaPath;
        String infrastructurePath = projectName+moduleName+"-infrastructure/src/"+javaPath;
        String mybatisPath = projectName+moduleName+"-infrastructure/src/main/resources/mapper";
        if (template.equals("vm/java/client/addcmd.java.vm"))
        {
            fileName = StringUtils.format("{}/client/{}/request/{}AddCmd.java", clientPath,businessName, className);
        }
        if (template.equals("vm/java/app/addcmdexe.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/executor/command/{}AddCmdExe.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/app/cmdconvertor.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/convertor/{}CmdConvertor.java", appPath, businessName,className);
        }
        if (template.equals("vm/java/client/co.java.vm"))
        {
            fileName = StringUtils.format("{}/client/{}/response/{}Co.java", clientPath, businessName,className);
        }
        if (template.equals("vm/java/adapter/controller.java.vm"))
        {
            fileName = StringUtils.format("{}/adapter/controller/web/{}Controller.java", adapterPath, className);
        }
        if (template.equals("vm/java/adapter/controllertree.java.vm"))
        {
            fileName = StringUtils.format("{}/adapter/controller/web/{}Controller.java", adapterPath, className);
        }
        if (template.equals("vm/java/app/delcmdexe.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/executor/command/{}DelCmdExe.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/infrastructure/do.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/persistence/domainobject/{}DO.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/infrastructure/doconvertor.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/convertor/{}DoConvertor.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/domain/domaine.java.vm"))
        {
            fileName = StringUtils.format("{}/domain/{}/model/{}E.java", domainPath,businessName, className);
        }
        if (template.equals("vm/java/domain/domainvo.java.vm"))
        {
            fileName = StringUtils.format("{}/domain/{}/model/vo/{}VO.java", domainPath,businessName, className);
        }
        //todo 修改
        /*if (template.equals("vm/java/domain/domainservice.java.vm"))
        {
            fileName = StringUtils.format("{}/domain/{}/ability/{}Ability.java", domainPath,businessName, className);
        }*/
        if (template.equals("vm/java/domain/domainability.java.vm"))
        {
            fileName = StringUtils.format("{}/domain/{}/ability/{}Ability.java", domainPath,businessName, className);
        }
        if (template.equals("vm/java/domain/gateway.java.vm"))
        {
            fileName = StringUtils.format("{}/domain/{}/gateway/{}Gateway.java", domainPath, businessName,className);
        }
        if (template.equals("vm/java/infrastructure/gatewayimpl.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/gateway/{}GatewayImpl.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/app/listqueryexe.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/executor/query/{}ListQueryExe.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/infrastructure/mapper.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/persistence/mapper/{}Mapper.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/client/pageqry.java.vm"))
        {
            fileName = StringUtils.format("{}/client/{}/request/{}PageQry.java", clientPath,businessName, className);
        }
        if (template.equals("vm/java/app/pagequeryexe.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/executor/query/{}PageQueryExe.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/infrastructure/queryservice.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/persistence/queryservice/{}QueryService.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/infrastructure/queryserviceimpl.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/persistence/queryservice/impl/{}QueryServiceImpl.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/infrastructure/repositoryimpl.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/persistence/repository/impl/{}RepositoryImpl.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/infrastructure/repository.java.vm"))
        {
            fileName = StringUtils.format("{}/infrastructure/persistence/repository/{}Repository.java", infrastructurePath, className);
        }
        if (template.equals("vm/java/app/servicei.java.vm" ))
        {
            fileName = StringUtils.format("{}/app/{}/service/{}ServiceI.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/app/serviceimpl.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/service/impl/{}ServiceImpl.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/client/treequery.java.vm"))
        {
            fileName = StringUtils.format("{}/client/{}/request/{}TreeQry.java", clientPath,businessName, className);
        }
        if (template.equals("vm/java/app/treequeryexe.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/executor/query/{}TreeQueryExe.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/app/treeservicei.java.vm" ))
        {
            fileName = StringUtils.format("{}/app/{}/service/{}ServiceI.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/app/treeserviceimpl.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/service/impl/{}ServiceImpl.java", appPath,businessName, className);
        }
        if (template.equals("vm/java/client/updatecmd.java.vm"))
        {
            fileName = StringUtils.format("{}/client/{}/request/{}UpdateCmd.java",clientPath,businessName, className);
        }
        if (template.equals("vm/java/app/updatecmdexe.java.vm"))
        {
            fileName = StringUtils.format("{}/app/{}/executor/command/{}UpdateCmdExe.java", appPath,businessName, className);
        }
        if (template.equals("vm/xml/mapper.xml.vm"))
        {
            fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath,className);
        }
        if(genTable.isHasEnum()){
            if (template.equals("vm/java/enums/enum.java.vm"))
            {
                fileName = StringUtils.format("{}/enums/{}/{}.java", enumPath,businessName,genTable.getEnumClassName());
            }
        }
        return fileName;
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName)
    {
        int lastIndex = packageName.lastIndexOf(".");
        String basePackage = StringUtils.substring(packageName, 0, lastIndex);
        return basePackage;
    }

    /**
     * 根据列类型获取导入包
     * 
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTable genTable)
    {
        List<GenTableColumn> columns = genTable.getColumns();
        GenTable subGenTable = genTable.getSubTable();
        HashSet<String> importList = new HashSet<String>();
        if (StringUtils.isNotNull(subGenTable))
        {
            importList.add("java.util.List");
        }
        for (GenTableColumn column : columns)
        {
            if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType()))
            {
                importList.add("java.util.Date");
                importList.add("com.fasterxml.jackson.annotation.JsonFormat");
            }
            else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType()))
            {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName 模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName)
    {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

    /**
     * 获取上级菜单ID字段
     *
     * @param paramsObj 生成其他选项
     * @return 上级菜单ID字段
     */
    public static String getParentMenuId(JSONObject paramsObj)
    {
        if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID))
        {
            return paramsObj.getString(GenConstants.PARENT_MENU_ID);
        }
        return DEFAULT_PARENT_MENU_ID;
    }

    /**
     * 获取树编码
     *
     * @param paramsObj 生成其他选项
     * @return 树编码
     */
    public static String getTreecode(JSONObject paramsObj)
    {
        if (paramsObj.containsKey(GenConstants.TREE_CODE))
        {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树父编码
     *
     * @param paramsObj 生成其他选项
     * @return 树父编码
     */
    public static String getTreeParentCode(JSONObject paramsObj)
    {
        if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE))
        {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取树名称
     *
     * @param paramsObj 生成其他选项
     * @return 树名称
     */
    public static String getTreeName(JSONObject paramsObj)
    {
        if (paramsObj.containsKey(GenConstants.TREE_NAME))
        {
            return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取需要在哪一列上面显示展开按钮
     *
     * @param genTable 业务表对象
     * @return 展开按钮列序号
     */
    public static int getExpandColumn(GenTable genTable)
    {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String treeName = paramsObj.getString(GenConstants.TREE_NAME);
        int num = 0;
        for (GenTableColumn column : genTable.getColumns())
        {
            if (column.isList())
            {
                num++;
                String columnName = column.getColumnName();
                if (columnName.equals(treeName))
                {
                    break;
                }
            }
        }
        return num;
    }

}
